package com.tz.pay.weixin.core.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import com.tz.util.MD5Util;

public class PayCommonUtil {  
    
    /** 
     * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。 
     * @return boolean 
     */  
    public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {  
        StringBuffer sb = new StringBuffer();  
        Set es = packageParams.entrySet();  
        Iterator it = es.iterator();  
        while(it.hasNext()) {  
            Map.Entry entry = (Map.Entry)it.next();  
            String k = (String)entry.getKey();  
            String v = (String)entry.getValue();  
            if(!"sign".equals(k) && null != v && !"".equals(v)) {  
                sb.append(k + "=" + v + "&");  
            }  
        }  
          
        sb.append("key=" + API_KEY);  
          
        //算出摘要  
        String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();  
        String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();  
          
        //System.out.println(tenpaySign + "    " + mysign);  
        return tenpaySign.equals(mysign);  
    }  
  
    /** 
     * @author 
     * @date 2016-4-22 
     * @Description：sign签名 
     * @param characterEncoding 
     *            编码格式 
     * @param parameters 
     *            请求参数 
     * @return 
     */  
    public static String createSign(String characterEncoding, Map<Object, Object> sParaTemp, String API_KEY) {  
        StringBuffer sb = new StringBuffer();  
        Set es = sParaTemp.entrySet();  
        Iterator it = es.iterator();  
        while (it.hasNext()) {  
            Map.Entry entry = (Map.Entry) it.next();  
            String k = (String) entry.getKey();  
            String v = (String) entry.getValue();  
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {  
                sb.append(k + "=" + v + "&");  
            }  
        }  
        sb.append("key=" + API_KEY); 
        System.out.println(sb);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();  
        return sign;  
    }
    
    public static String createSign2(String characterEncoding,Map<Object,Object> parameters,String api_key){
    	String signString="appid="+parameters.get("appid")+"&body="+parameters.get("body")+"&mch_id="+parameters.get("mch_id")+"&nonce_str="+parameters.get("nonce_str")+"&notify_url="+parameters.get("notify_url")+"&out_trade_no="+parameters.get("out_trade_no")+"&product_id="+parameters.get("product_id")
    			+"&spbill_create_ip="+parameters.get("spbill_create_ip")+"&total_fee="+parameters.get("total_fee")+"&trade_type="+parameters.get("trade_type")+"&key="+api_key;
    	
		String sign = MD5Util.MD5Encode(signString, characterEncoding).toUpperCase();
		return sign;
	}
  
    /** 
     * @author 
     * @date 2016-4-22 
     * @Description：将请求参数转换为xml格式的string 
     * @param sParaTemp 
     *            请求参数 
     * @return 
     */  
    public static String getRequestXml(Map<String, String> sParaTemp) {  
        StringBuffer sb = new StringBuffer();  
        sb.append("<xml>");  
        Set es = sParaTemp.entrySet();  
        Iterator it = es.iterator();  
        while (it.hasNext()) {  
            Map.Entry entry = (Map.Entry) it.next();  
            String k = (String) entry.getKey();  
            String v = (String) entry.getValue();  
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {  
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");  
            } else {  
                sb.append("<" + k + ">" + v + "</" + k + ">");  
            }  
        }  
        sb.append("</xml>");  
        return sb.toString();  
    }  
  
    /** 
     * 取出一个指定长度大小的随机正整数. 
     *  
     * @param length 
     *            int 设定所取出随机数的长度。length小于11 
     * @return int 返回生成的随机数。 
     */  
    public static int buildRandom(int length) {  
        int num = 1;  
        double random = Math.random();  
        if (random < 0.1) {  
            random = random + 0.1;  
        }  
        for (int i = 0; i < length; i++) {  
            num = num * 10;  
        }  
        return (int) ((random * num));  
    }  
  
    /** 
     * 获取当前时间 yyyyMMddHHmmss 
     *  
     * @return String 
     */  
    public static String getCurrTime() {  
        Date now = new Date();  
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");  
        String s = outFormat.format(now);  
        return s;  
    }
    
    /**
     * google的二维码生成接口
     * 方法名：QRfromGoogle<BR>
     * 时间：2016年11月10日-下午10:12:53 <BR>
     * @param chl
     * @return
     * @throws Exception String<BR>
     * @exception <BR>
     * @since  1.0.0
     */
    public static String QRfromGoogle(String chl) throws Exception {  
        int widhtHeight = 300;  
        String EC_level = "L";  
        int margin = 0;  
        chl = UrlEncode(chl);  
        String QRfromGoogle = "http://chart.apis.google.com/chart?chs=" + widhtHeight + "x" + widhtHeight  
                + "&cht=qr&chld=" + EC_level + "|" + margin + "&chl=" + chl;  
      
        return QRfromGoogle;  
    }
    
 // 特殊字符处理  
    public static String UrlEncode(String src)  throws UnsupportedEncodingException {  
        return URLEncoder.encode(src, "UTF-8").replace("+", "%20");  
    }  
  
}  